package org.musicPlayerServer.business;

import java.util.List;

import javazoom.jl.player.advanced.PlaybackEvent;
import javazoom.jl.player.advanced.PlaybackListener;
import javazoom.jlgui.basicplayer.BasicPlayerException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.musicPlayerServer.business.object.Content;
import org.musicPlayerServer.business.object.Folder;
import org.musicPlayerServer.business.object.Music;
import org.musicPlayerServer.music.MusicPlayer;

public class Controller {

    Log log = LogFactory.getLog(getClass());


    Music currentMusic;
    Folder currentFolder;
    MusicPlayer mp;
    ContentManager cm;

    Boolean continueMode;

    String rootFolder;

    Boolean stopping = false;

    Controller me = this;

    static Controller soleInstance = new Controller();

    private Controller() {
    }

    /*PlaybackListener listener = new PlaybackListener(){

	@Override
	public void playbackFinished(PlaybackEvent arg0) {
	    log.info("playback Finished");
	    if(stopping){
		stopping = false;
	    }else if(continueMode){
		next();
		if(currentMusic!=null){
		    try {
			me.play();
		    } catch (Exception e) {
			log.error(e);
		    }
		}
	    }
	}

	@Override
	public void playbackStarted(PlaybackEvent arg0) {

	}

    };*/

    public static Controller getInstance() {
	return soleInstance;
    }

    public void init(String rootFolder){
	this.rootFolder = rootFolder;
	currentFolder = new Folder(rootFolder);
	mp = MusicPlayer.getInstance();
	cm = new ContentManager();
	continueMode= true;
	mp.setContentManager(cm);
	//mp.setListener(listener);
    }


    public void next() {
	Music m = cm.getNextMusic(currentMusic);

	log.info("nexting to :"+m.getFilePath());
	select(m);

    }

    public synchronized void play() throws Exception{
	mp.play();	    
    }

    public void pause() throws BasicPlayerException{
	mp.pause();
    }

    public void resume() throws BasicPlayerException{
	mp.resume();
    }

    public void stop() throws BasicPlayerException{
	mp.stop();
	/*if(mp.isMusicToStop()){
	    stopping = true;
	    mp.stop();
	}*/
    }

    public void select(Music file){
	currentMusic = file;
	if(currentMusic!=null){
	    mp.select(currentMusic);
	}
	//log.info("Next Music will be :"+cm.getNextMusic(currentMusic).getFilePath());
    }

    public Music getCurrent(){
	return currentMusic;
    }

    public void goToParentFolder(){
	if(!currentFolder.getFilePath().equals(rootFolder)){
	    currentFolder = currentFolder.getParentFolder(currentFolder);
	}
    }

    public List<Content> getContent() {
	return currentFolder.listContent();
    }

    public void moveToFolder(String folder) {
	if(folder==null){
	    currentFolder =new Folder(rootFolder);
	} else if(folder.equals("parent")){
	    goToParentFolder();
	}else{
	    currentFolder = new Folder(folder);
	}
    }

    public Folder getCurrentFolder() {
	return currentFolder;
    }
    


}
